/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package netoppiggy_server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import netoppiggy_interface.FormChat;

/**
 *
 * @author Dai
 */
public class ClientServiceThread implements Runnable {

    Socket m_clientSocket;
    int m_clientID = -1;
    boolean m_bRunThread = true;
    BufferedReader m_in = null;
    PrintWriter m_out = null;
    
    public ChatWithClientsForm _frmChat;

    public void sendMessage(String msg){
        m_out.println(msg);
    }
    
    public String receiveMessage(){
        try {
            return m_in.readLine();
        } catch (IOException ex) {
            return null;
        }
    }
    
    ClientServiceThread(Socket s, int clientID) {
        
        m_clientSocket = s;
        m_clientID = clientID;
        try {
            m_in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
            m_out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
        } catch (IOException ex) {
            Logger.getLogger(ClientServiceThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
   

    


    public void run() {
        BufferedReader in = null;
        System.out.println("Accepted Client : ID - " + m_clientID + " : Address - "
                + m_clientSocket.getInetAddress().getHostName());
        try {
            in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
            while (m_bRunThread) {
                // read incoming stream 
                String clientCommand = in.readLine();
                
                String text = "\nClient: " + clientCommand;
                this._frmChat._arrFormChat.get(this.m_clientID).appendText("\n" + clientCommand);
                if (clientCommand.equalsIgnoreCase("quit")) {
                    m_bRunThread = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Clean up 
            try {
                in.close();
                m_clientSocket.close();
                this._frmChat._arrFormChat.get(this.m_clientID).appendText("\nStopped");
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}
